package se.djupfeldt.oscar.logbook.datasource;
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.UnsupportedCommOperationException;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.log4j.Logger;

import se.djupfeldt.oscar.logbook.Logbook;

public class SerialComm extends DataSource {
    private InputStream input;
    private OutputStream output;
    private String string;
    private int baudRate;
    private int dataBits;
    private int stopBits;
    private int parity;
    private String serialPort;
    private String portOwner;
    private int portID;
    
    @Override
    protected void runLoop() {
	Logger.getLogger(getClass()).info("Serial input started.");
	string = "";
	for(;;) {
	    try {
		while (input.available()>0) {
		    char c = (char)(input.read());
		    string += c;
		    if (c == '\n') {
			list.add(string);
			string = "";
		    }
		}
	    } catch (IOException e) {
		e.printStackTrace();
	    }
	}
    }

    public SerialComm() {
    }

    public void init() {
	super.init();
	
	baudRate = Logbook.properties.getInt("baudRate", 4800);
	dataBits = Logbook.properties.getInt("dataBits", SerialPort.DATABITS_8);
	stopBits = Logbook.properties.getInt("stopBits", SerialPort.STOPBITS_1);
	parity = Logbook.properties.getInt("parity", SerialPort.PARITY_NONE);
	serialPort = Logbook.properties.getProperty("serialPort", "/dev/tty.usbmodem1421");
	
	portOwner = "Logbook";
	portID = 4000;
	
	try {
	    SerialPort port = (SerialPort) CommPortIdentifier.getPortIdentifier(serialPort).open(portOwner, portID);
	    Logger.getLogger(getClass()).info("Serial port opened. " + portOwner + ":" + portID + "@" + serialPort);
	    input = port.getInputStream();
	    output = port.getOutputStream();

	    port.setSerialPortParams(baudRate, dataBits, stopBits, parity);
	} catch (PortInUseException e) {
	    log.error(e.getMessage(), e);
	    System.exit(-1);
	} catch (NoSuchPortException e) {
	    log.error(e.getMessage(), e);
	    System.exit(-1);
	} catch (IOException e) {
	    log.error(e.getMessage(), e);
	    System.exit(-1);
	} catch (UnsupportedCommOperationException e) {
	    log.error(e.getMessage(), e);
	    System.exit(-1);
	}
    }
    
    public int getBaudRate() {
	return baudRate;
    }
    
    public int getDataBits() {
	return dataBits;
    }
    
    public InputStream getInput() {
	return input;
    }
    
    public OutputStream getOutput() {
	return output;
    }
    
    public int getParity() {
	return parity;
    }
    
    public int getStopBits() {
	return stopBits;
    }
    
    public int getPortID() {
	return portID;
    }
    
    public String getPortOwner() {
	return portOwner;
    }
    
    public String getSerialPort() {
	return serialPort;
    }
}